// ==UserScript==
// @name         ZFT验证码自动识别填写
// @namespace    your_namespace
// @version      1.7
// @description  ZFT验证码自动识别填写
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// @connect      10.0.0.3
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    const API_ENDPOINT = 'https://api.nonex.top/captcha/code';
    const SELECTORS = {
        input: '#validateCode',
        image: '.ant-col-8 img'
    };

    // 数据持久化存储
    let captchaCache = null;

    function captureCanvasData(img) {
        const canvas = document.createElement('canvas');
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        return canvas.toDataURL('image/png', 1.0).split(',')[1];
    }

    function setInputValue(input, value) {
        input.value = value;
        // 触发所有可能需要的表单事件
        ['input', 'change', 'blur'].forEach(eventType => {
            const event = new Event(eventType, { 
                bubbles: true,
                cancelable: true
            });
            input.dispatchEvent(event);
        });
    }

    async function handleFocus() {
        const input = document.querySelector(SELECTORS.input);
        const image = document.querySelector(SELECTORS.image);
        
        if (!input || !image) return;

        try {
            const base64Data = captureCanvasData(image);
            
            GM_xmlhttpRequest({
                method: "POST",
                url: API_ENDPOINT,
                data: JSON.stringify({ ImageBase64: base64Data }),
                headers: { "Content-Type": "application/json" },
                onload: (response) => {
                    try {
                        const result = JSON.parse(response.responseText);
                        if (result.status === 'success') {
                            captchaCache = result.result;
                            setInputValue(input, result.result);
                            // 延迟二次填充确保值稳定
                            setTimeout(() => {
                                if (input.value !== result.result) {
                                    setInputValue(input, result.result);
                                }
                            }, 300);
                        }
                    } catch(e) {
                        console.error('解析失败:', e);
                    }
                }
            });
        } catch(e) {
            console.error('处理失败:', e);
        }
    }

    // 新增输入框值监控
    function initValueGuard() {
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (mutation.attributeName === 'value' && captchaCache) {
                    const currentValue = mutation.target.value;
                    if (currentValue !== captchaCache) {
                        setInputValue(mutation.target, captchaCache);
                    }
                }
            });
        });

        const input = document.querySelector(SELECTORS.input);
        if (input) {
            observer.observe(input, { 
                attributes: true,
                attributeFilter: ['value']
            });
        }
    }

    function init() {
        const input = document.querySelector(SELECTORS.input);
        if (input) {
            input.addEventListener('focus', handleFocus);
            initValueGuard(); // 初始化值监控
        } else {
            setTimeout(init, 500);
        }
    }

    if (document.readyState === 'complete') {
        init();
    } else {
        window.addEventListener('load', init);
    }
})();